package com.fand.manager.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import com.fand.common.exception.BusinessException;
import com.fand.common.util.JsonUtils;
import com.fand.common.util.PageResult;
import com.fand.manager.model.active.SysUserIndexRecordSearchDTO;
import com.fand.manager.service.ISysUserIndexRecordService;
import com.fand.stater.constant.EventCodeEnum;
import com.fand.stater.constant.FandIndexConstant;
import com.fand.stater.model.es.SysUserESIndexRecord;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/27
 * Version: 1.0
 */
@Slf4j
@Service
public class SysUserIndexRecordServiceImpl implements ISysUserIndexRecordService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @SneakyThrows
    @Override
    public PageResult<List<SysUserESIndexRecord>> list(SysUserIndexRecordSearchDTO sysUserIndexRecordSearchDTO) {
        if(Objects.isNull(sysUserIndexRecordSearchDTO)){
            throw new BusinessException("非法参数");
        }
        List<SysUserESIndexRecord> listDatas = CollUtil.newArrayList();
        //默认查询当天
        Date startDateTime = sysUserIndexRecordSearchDTO.getStartDateTime();
        Date endDateTime = sysUserIndexRecordSearchDTO.getEndDateTime();
        Long start = null;
        Long end = null;
        if(Objects.isNull(startDateTime)){
            startDateTime = DateUtil.beginOfDay(new Date());
        }
        start = startDateTime.getTime();
        if(Objects.isNull(endDateTime)){
            endDateTime = DateUtil.endOfDay(new Date());
        }
        end = endDateTime.getTime();

        SearchRequest searchRequest = new SearchRequest(FandIndexConstant.FAND_USER_COLLECTION_RECORD);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.filter(QueryBuilders.rangeQuery("time").gte(start).lte(end));

        if(Objects.nonNull(sysUserIndexRecordSearchDTO.getUserCode())){
            queryBuilder.must(QueryBuilders.termQuery("userCode.keyword",sysUserIndexRecordSearchDTO.getUserCode()));
        }
        if(Objects.nonNull(sysUserIndexRecordSearchDTO.getUserName())){
            queryBuilder.must(QueryBuilders.termQuery("userName.keyword",sysUserIndexRecordSearchDTO.getUserName()));
        }
        queryBuilder.must(QueryBuilders.termQuery("eventCode.keyword", EventCodeEnum.INDEX.getCode()));

        searchSourceBuilder.from((sysUserIndexRecordSearchDTO.getPage()-1)*sysUserIndexRecordSearchDTO.getLimit()).size(sysUserIndexRecordSearchDTO.getLimit());
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort("time", SortOrder.DESC);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit[] hits = searchResponse.getHits().getHits();
        if(ArrayUtil.isNotEmpty(hits)){
            Arrays.stream(hits).forEach(hit ->{
                SysUserESIndexRecord sysUserESIndexRecord = JsonUtils.jsonToPojo(hit.getSourceAsString(), SysUserESIndexRecord.class);
                listDatas.add(sysUserESIndexRecord);
            });
        }
        return new PageResult(Integer.parseInt(String.valueOf(searchResponse.getHits().getTotalHits().value)),listDatas);
    }

}
